package com.mes.web.controller.jy;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mes.entity.hy.Product;
import com.mes.entity.jy.CustomerOrderAndDetailjy;
import com.mes.entity.jy.CustomerOrderjy;
import com.mes.entity.jy.DaysheduDetail;
import com.mes.entity.jy.Plandetail;
import com.mes.entity.jy.Planjy;
import com.mes.entity.jy.Queryjy;
import com.mes.service.jy.ProductPlanDetailServise;
import com.mes.service.jy.ProductPlanServise;
import com.mes.utils.ResponseUtil;

/**
 * @ClassName: ProductPlanController 
 * @Description:生产计划单的Controller
 * @Author jy
 * @Date 2017年12月20日 下午2:42:34 
 * @version 1.0
 */
@Controller
@RequestMapping("/jy")
public class ProductPlanController {

	@Resource
	private ProductPlanServise productPlanServise;
	@Resource
	private ProductPlanDetailServise productPlanDetailServise;
	
	/**
	 * 去添加页面
	 * @return 生产计划添加页面
	 */
	@RequestMapping("/toCreateplan")
	public String toCreateplan() {
		return "jyy/createplan";
	}
	
	/**
	 * 添加生产计划单
	 * @param planjy 生产计划实体
	 * @param response 响应
	 * @throws IOException 输入输出异常
	 */
	@RequestMapping("/createPlan")
	public void createPlan(Planjy planjy,HttpServletResponse response) throws IOException {
		
		//在添加前删除冗余详情数据
		/*productPlanDetailServise.deleteNumNotin();*/
		
		//获取当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String format = dateFormat.format(new Date());
		//生产计划单日期
		planjy.setRemark(format);
		planjy.setState("未提交");
		//保存
		int affact = productPlanServise.createPlan(planjy);
		//根据计划单编号在详情表中查到对应销售单id，修改其状态为：
		productPlanServise.editSstate1(planjy.getPlannum());
		response.getWriter().print(affact);
	}
	
	/**
	 * 去修改页面
	 * @param id 生产计划id
	 * @param model 返回页面封装数据的实体类
	 * @return 修改生产计划列表
	 */
	@RequestMapping("/toEditplan")
	public String toEditplan(long id,Model model) {
		//根据id查询生产计划单
		Planjy planjy = productPlanServise.selectProductPlanByid(id);
		model.addAttribute("planjy", planjy);
 		return "jyy/editplan";
	}
	
	
	/**
	 * 删除生产计划单
	 * @param pids 批量删除生产计划
	 * @param response 响应
	 * @throws IOException 输入输出异常
	 */
	@RequestMapping("/deletePlan")
	public void deletePlan(String pids,HttpServletResponse response) throws IOException {
		
		/*删除生产计划单时，要将销售计划单的状态改回去（1->0）*/
		String[] pids2 = pids.split(",");
		for (String pid : pids2) {
			long id = Long.valueOf(pid);
			Planjy planjy = productPlanServise.selectProductPlanByid(id);
			CustomerOrderjy customerOrderjy = new CustomerOrderjy();
			customerOrderjy.setProducestatus("0");
			customerOrderjy.setId(Long.valueOf(planjy.getRemark1()));
			productPlanServise.editSstate3(customerOrderjy);
			
			customerOrderjy = null;
		}
		
		//删除
		int affact = productPlanServise.deletePlan(pids);
		
		response.getWriter().print(affact);
	}
	
	/**
	 * 带条件的分页查询生产计划
	 * @param queryjy 条件查询实体
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectPlan")
	public void selectPlan(Queryjy queryjy,HttpServletResponse response) throws Exception {
		
		//条件判空
		/*if(queryjy.getState()!= null) {
			
			String state = queryjy.getState();
			state = new String(state .getBytes("iso8859-1"),"utf-8");
			queryjy.setState(state);
		}*/
		
		//统计总数
		int count = productPlanServise.countProductPlan(queryjy);
		//条件查询
		List<Planjy> list = productPlanServise.selectProductPlanPagein(queryjy);
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 根据生产计划单号查询生产计划单详情
	 * @param plannum 生产计划单号
	 * @param salenum 销售计划量
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectPlanDetail")
	public void selectPlanDetail(String plannum,String salenum,HttpServletResponse response) throws Exception {
		
		//实际量
		Integer num  = 0;
		//计划量
		Integer plnum = 0;
		//剩余数量
		Integer snum = 0;
		
		int count = productPlanDetailServise.countProductPlanDetail(plannum);
	    List<Plandetail> list= productPlanDetailServise.selectPlanDetail(plannum);
	    for (Plandetail plandetail : list) {
	    	//根据销售计划单id|查询销售计划单号
	    	plandetail.setRemartk4(salenum);
	    	//根据根据销售计划单详情id查询销售计划量
	    	String sdetailid = plandetail.getRemartk9();
	    	int dplannum= productPlanServise.selectsaleDetaiplannuml(sdetailid);
	    	//销售计划量
	    	plandetail.setRemartk3(dplannum+"");
	    	
	    	//根据产品id()查库存表，获得库存量(库存中会有很多条，根据id统计)
			String pcount = productPlanServise.countProductNum(Long.valueOf(plandetail.getRemartk()));
			plandetail.setRemartk14(pcount);
	    	
	    	
	    	//当前完成数量、剩余数量(根据计划详情id查询)
			List<String> snum2s = productPlanServise.selectWorkBypid(plandetail.getId());
			for (String snum2 : snum2s) {
				if(snum2 != null && snum2 != "") {
					//实际量
		    		num = num + Integer.valueOf(snum2);
		    	}
			}//第二层for
			
			//根据（remark1）
    		List<String> snum3s = productPlanServise.selectWorkBypid2(plandetail.getId());
    		for (String snum3 : snum3s) {
    			if(snum3 != null && snum3 != "") {
    				//实际量
	    			 num = num + Integer.valueOf(snum3);
	    		}
			}//第二层for
    		
			//实际量
    		plandetail.setNnum(num+"");
    		//计划量
    		plnum = Integer.valueOf(plandetail.getRemartk1());
    		if(plnum != null) {
    			if(num != null) {
    				snum = plnum-num;
    	    		//剩余数量
    	    		plandetail.setSnum(snum+"");
    			}
    		}
			
    		snum2s = null;
    		snum3s = null;
    		num  = 0;
    		plnum = 0;
    		snum = 0;
		}//第一层for
	    
	    JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	
	/**
	 * 根据销售计划单id查询销售计划单详情
	 * @param sid 销售计划单id
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("selectSalePlanDetailBysid")
	public void selectSalePlanDetailBysid(Long sid,HttpServletResponse response) throws Exception {
		
		//根据客户订单id统计订单详情总记录数
		int count = productPlanServise.countCostomerOrderDetail(sid);
		
		//根据客户订单id查询客户订单详情
		//1.查中间表得出详情表的产品id的list集合
		List<CustomerOrderAndDetailjy> list1 = productPlanServise.seselectSalePlanDetailBysid(sid);
		
		List<Product> list = new ArrayList<Product>();
		//遍历集合，根据产品id查询产品表中产品的详情
		for (CustomerOrderAndDetailjy customerOrderAndDetailjy : list1) {
			//获得每个产品的销售计划量
			Integer salePlannun = customerOrderAndDetailjy.getPlanq();
			//产品id
			Long productorid = customerOrderAndDetailjy.getProductorid();
			
			//页面需求信息：车种，品编，品名，颜色，安全库存量(remark3)
			//根据产品id查产品表中的基本信息
			Product produc= productPlanServise.selsectProductByid(productorid);
			//销售计划量
			if(salePlannun!= null) {
				produc.setRemark3(salePlannun+"");
			}
			//根据产品id()查库存表，获得库存量(库存中会有很多条，根据id统计)
			String pcount = productPlanServise.countProductNum(productorid);
			if(pcount != null) {
				produc.setRemark14(pcount);
			}else {
				produc.setRemark14(0+"");
			}
			//销售单详情id
			produc.setRemark9(customerOrderAndDetailjy.getId().toString());
			//生产计划量
			produc.setRemark7("");
			//要求完工日期finishDate
			produc.setRemark8(customerOrderAndDetailjy.getFinishDate());
			list.add(produc);
		}
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 查询所有的客户订单（带条件的分页）
	 * @param queryjy 条件查询
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectCustomerOrder")
	public void selectCustomerOrder(Queryjy queryjy,HttpServletResponse response) throws Exception {
		//统计所有的客户订单
		int count = productPlanServise.countCustomerOrder(queryjy);
		//分页查询
		List<CustomerOrderjy> list = productPlanServise.customerOrderPagine(queryjy);
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 添加生产计划单明细
	 * @param prductid 产品id
	 * @param plannum 生产计划量
	 * @param fdata 要求完工日期
	 * @param scjhdh 生产计划单号
	 * @param sid 销售计划单id
	 * @param remark9 生产计划单详情id
	 * @param response 相应
	 * @throws Exception 异常
	 */
	@RequestMapping("/createProductPlanDetail")
	public void createProductPlanDetail(String prductid,String plannum,String fdata,String scjhdh,Long sid,String remark9,HttpServletResponse response) throws Exception {
		Plandetail planDetail = new Plandetail();
		//产品id
		planDetail.setRemartk(prductid);
		//生产计划量
		planDetail.setRemartk1(plannum);
		//要求完工日期
		planDetail.setPwdate(fdata);
		//生产计划单号
		planDetail.setPlannum(scjhdh);
		//销售计划单id
		planDetail.setSid(sid);
		//生产计划单详情id
		planDetail.setRemartk9(remark9);
		//初始化是否已做采购计划
		planDetail.setRemartk13("0");
		//初始化完成状态
		planDetail.setWstape("未排产");
		int  affact= productPlanDetailServise.createOrupdateDetaile(planDetail);
		ResponseUtil.write(response, affact);
	}
	
	/**
	 * 根据生产计划单单号查询生产计划单的详情
	 * @param plannum 生产计划单号
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectPlanDetailByPlannum")
	public void selectPlanDetailByPlannum(String plannum,HttpServletResponse response) throws Exception {
		int count = productPlanDetailServise.countProductPlanDetail(plannum);
		List<Plandetail> list =	productPlanDetailServise.selectPlanDetail(plannum); 
		
		for (Plandetail plandetail : list) {
			Product product = productPlanServise.selsectProductByid(Long.valueOf(plandetail.getRemartk()));
			
			//车种
			plandetail.setCartype(product.getCartype());
			//品编
			plandetail.setPnum(product.getNum());
			//品名
			plandetail.setPname(product.getName());
			//周期
			plandetail.setRemartk2(product.getRemark6());
		}
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 根据生产计划单单号查询生产计划单的详情
	 * @param plannum 生产计划单号
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectPlanDetailByPlannum2")
	public void selectPlanDetailByPlannum2(String plannum,HttpServletResponse response) throws Exception {
		//统计
		int count = productPlanDetailServise.countProductPlanDetail2(plannum);
		//分页查询
		List<Plandetail> list =	productPlanDetailServise.selectPlanDetail2(plannum); 
		
		for (Plandetail plandetail : list) {
			Product product = productPlanServise.selsectProductByid(Long.valueOf(plandetail.getRemartk()));
			
			//车种
			plandetail.setCartype(product.getCartype());
			//品编
			plandetail.setPnum(product.getNum());
			//品名
			plandetail.setPname(product.getName());
			//周期
			plandetail.setRemartk2(product.getRemark6());
			//模数
			plandetail.setRemartk8(product.getModulus());
		}
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 根据选中的多个生产计划详情id查询生产计划详情列表
	 * @param ids  选中的多个生产计划详情id
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectPlanDetailByids")
	public void selectPlanDetailByids(String ids,HttpServletResponse response) throws Exception {
	
		
		//排产单详情
		List<DaysheduDetail> list = new ArrayList<DaysheduDetail>();
		
		String[] ids2 = ids.split(",");
		int count  = ids2.length;
		for (String s : ids2) {
			Long id = Long.valueOf(s);
			//根据id查询计划单详情
			Plandetail plandetail= productPlanDetailServise.slectPlanDetailByid(id);
			//根据id查询产品信息
			Product product = productPlanServise.selsectProductByid(Long.valueOf(plandetail.getRemartk()));
			//排产单详情实体
			DaysheduDetail daysheduDetail = new DaysheduDetail();
			
			//产品id
			daysheduDetail.setRemark(product.getPid().toString());
			//车种
			daysheduDetail.setCartype(product.getCartype());
			//品编
			daysheduDetail.setPnum(product.getNum());
			//品名
			daysheduDetail.setPname(product.getName());
			//周期
			daysheduDetail.setCycle(product.getRemark6());
			//模数
			daysheduDetail.setRemark8(product.getModulus());
			//状态
			daysheduDetail.setState(plandetail.getWstape());
			//未排产生产计划量
			daysheduDetail.setRemark6(plandetail.getRemartk11());
			//计划量
			daysheduDetail.setPlannum(plandetail.getRemartk10());
			//计划完工日期
			daysheduDetail.setRemark4(plandetail.getPwdate());
			daysheduDetail.setStattime(plandetail.getRemartk7());
			daysheduDetail.setEndtime(plandetail.getRemartk8());
			
			//对应计划单详情id
			daysheduDetail.setRemark5(s );
			
			list.add(daysheduDetail);
		}
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 导出（此功能暂时未实现）
	 * @param queryjy 条件查询实体
	 * @param response 响应
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/exportProductPlan")
	public void exportDayshedu(Queryjy queryjy,HttpServletResponse response) throws UnsupportedEncodingException {
		
	}
	
	/**
	 * 关闭计划单详情
	 * @param plandetail 计划单详情
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/shutdwonPlandetail")
	public void shutdwonPlandetail(Plandetail plandetail,HttpServletResponse response) throws Exception {
		int affact = 0;
		//根据id修改生产计划单的完成状态 为关闭
		plandetail.setWstape("关闭");
		affact= productPlanDetailServise.editWstape(plandetail) ;
		ResponseUtil.write(response, affact);
	}
	
	/**
	 * 发起生产计划申请，修改计划单状态
	 * @param ids  计划单id字符串
	 * @param response 响应
	 * @param request 请求
	 * @throws IOException 输入输出异常
	 */
	@RequestMapping("/startApply")
	public void startApply(String ids,HttpServletResponse response,HttpServletRequest request) throws IOException{
		String[] split = ids.split(",");
		for (String s : split) {
			Long id = Long.valueOf(s);
			
			//修改审核状态
			Planjy planjy = new Planjy();
			planjy.setState("审批完成");
			planjy.setRemark3("");
			planjy.setId(id);
			//根据id修改审批状态，以及审批流程id
			productPlanServise.editPlanState(planjy);
			//提交成功！
		}
		response.getWriter().print(1);
		
	}//方法结束
	
	
	/**
	 *  查询此生产计划单中有没有详情
	 * @param plannum 生产计划单号
	 * @param response 响应
	 * @throws IOException 输入输出异常
	 */
	@RequestMapping("selectPlanDetail2")
	public void selectPlanDetail2(String plannum,HttpServletResponse response) throws IOException {
		List<Plandetail> list = productPlanDetailServise.selectPlanDetail(plannum);
		if(list.size() > 0) {
			response.getWriter().print(1);
		}else {
			response.getWriter().print(0);
		}
	}
	
}
